$("#formSave").keyup(function(event){
	keyCode = event.which;
});
$("#formSave").validator({
	stopOnError: "true",
	ignore:":hidden"
});
$('[name="mingcheng"]').focus();
// pointer2/3点击时添加（解决光标定在药品时点击删除保存不了的问题）
var xuanzeypFlagbf = true;
$(function () {
	/**正则判断字符数*/
	function getByteLen(val) {
		var len = 0;
		for (var i = 0; i < val.length; i++) {
			var a = val.charAt(i);
			if (a.match(/[^\x00-\xff]/ig) != null) {
				len += 2;
			} else {
				len += 1;
			}
		}
		return len;
	}
	//数量单位可输入
	$(document).on("blur","[name='kaiyaodw']",function(){
		var kaiyaodw = $(this).val();
		if(getByteLen(kaiyaodw) > 4) {
				notifyWarning('请输入1-2个字符');
				this.focus();
				$(this).addClass("n-invalid");
				return false;
			}else{
				$(this).removeClass("n-invalid");
		}
	});
	//数量单位可输入
	$(document).on("blur","[name='danwei']",function(){
		var danwei = $(this).val();
		if(getByteLen(danwei) > 4) {
				notifyWarning('请输入1-2个字符');
				this.focus();
				$(this).addClass("n-invalid");
				return false;
			}else{
				$(this).removeClass("n-invalid");
		}
	});
	//数量单位可输入
	$(document).on("blur","[name='dancijldw']",function(){
		var danwei = $(this).val();
		if(getByteLen(danwei) > 4) {
				notifyWarning('请输入1-2个字符');
				this.focus();
				$(this).addClass("n-invalid");
				return false;
			}else{
				$(this).removeClass("n-invalid");
		}
	});
	 $(document).on("mouseover",".pointer2",function(){
	      $(this).popover('show');
	  });
	$(document).on("mouseout",".pointer2",function(){
	      $(this).popover('hide');
	  });
	$(document).on("mouseover",".pointer3",function(){
	      $(this).popover('show');
	  });
	$(document).on("mouseout",".pointer3",function(){
	      $(this).popover('hide');
	  });
	// li标签传值
	$(document).on("mouseover",".dropdown-menu li",function(){
		$(this).addClass("hello");
	});
	$(document).on("mouseout",".dropdown-menu li",function(){
		$(this).removeClass("hello");
	});
//input模拟select模拟
 $(document).on('focusin',".dropdown-toggle",function(){
    $(this).siblings(".dropdown-menu").css("display","block");
 });
 //btn模拟select模拟
$(document).on("focusout",".dropdown-toggle",function(){
	if($(".dropdown-menu li").hasClass("hello")){
		$(this).siblings(".dropdown-menu").css("display","block");
	}else{
		$(this).siblings(".dropdown-menu").css("display","none");
	}
});

 $(document).on("click",".kaiyaodw li",function(){
    var bText = $(this).text();
    $(this).parent().siblings(".dropdown-toggle").val(bText).removeClass("n-invalid");
    $(this).parent().parent().parent().find('[name="danwei"]').val(bText);
    $(this).parent(".dropdown-menu").css("display","none");
    $(this).parent().parent().parent().parent().find("input:visible:not('.wm-group,[name=\"beizhu\"]')").each(function(){
		if($(this).val()==""){
			$(this).focus();
			return false;
		}
	});
 });
 //组号选择
 $(document).on("click",".cgmz-jcts li",function(){
	    var bText = $(this).text();
	    $(this).parent().siblings(".dropdown-toggle").val(bText).removeClass("n-invalid");;
	    $(this).parent(".dropdown-menu").css("display","none");
	    $(this).parent().parent().parent().parent().find("input:visible:not('.wm-group')").each(function(){
			if($(this).val()==""){
				$(this).focus();
				return false;
			}
		});
});
 /*成药每次剂量为适量时，数量不可编辑*/
 $(document).on("click",".dancijldw li",function() { 
  	var bText = $(this).text();
  	 $(this).parent().siblings(".dropdown-toggle").val(bText).removeClass("n-invalid");;
      $(this).parent(".dropdown-menu").css("display","none");
 	var _text = $(this).parent().prev(".cgmdc-input52").val();
 	if(_text == "适量"){
 		$(this).parent().prev().prev(".cgmdc-input51").attr('disabled',true).val('').removeClass("n-invalid");;
 		 $(this).parent().parent().parent().parent().find("input:visible:not(.wm-group,.cgmdc-input51,[name=\"beizhu\"])").each(function(){
 			if($(this).val()==""){
 				$(this).focus();
 				return false;
 			}
 		});
 	}else{
 		$(this).parent().prev().prev(".cgmdc-input51").attr('disabled',false);
 		 $(this).parent().parent().parent().parent().find("input:visible:not('.wm-group,[name=\"beizhu\"]')").each(function(){
 			if($(this).val()==""){
 				$(this).focus();
 				return false;
 			}
 		});
 	}
   
 });

});

//精确查找商品
//药品
//$(document).off('click', '#jingqueczspyp');
//$(document).on('click','#jingqueczspyp',function(){
//	var mingcchen = $(this).parent().parent().find(".yaopinmc").val();
//	$('#shangpinmc').val('');
//	$(this).parent().parent().find(".yaopinmc").val('').addClass('qiaojie xinjianmb');
//	$(this).parent().parent().parent().find(".yaopinmc").val('').addClass('qiaojie');
//	$(this).parent().parent().parent().find(".g-wmfinp-warning").css('display','none');
//	$(this).parent().parent().parent().find(".g-wmfinp-danger").css('display','none');
//	if($(this).parents('.western-medicine').css('display') == 'block'){
//		$(this).parent().parent().parent().find(".cgmdc-input3").val('');
//		$(this).parent().parent().parent().find(".cgmdc-input4").val('');
//		$(this).parent().parent().parent().find(".cgmdc-input51").val('');
//		$(this).parent().parent().parent().find(".cgmdc-input52").val('');
//		$(this).parent().parent().parent().find(".cgmdc-input61").val('');
//		$(this).parent().parent().parent().find(".cgmdc-input62").val('').attr('readonly',false);
//		$('.check').removeClass("check2").addClass("check1");
//		$('#checkHaocai').parent().parent('.modal-seh-leixing').css('display','block');
//		$('.chazhc').css('display','none');
//		$('.chazcy').css('display','none');
//	}else{
//		$(this).parent().parent().parent().find("[name='danjiliang']").val('');
//		$(this).parent().parent().parent().find("[name='danwei']").val('').attr('readonly',false);
//		$(this).parent().parent().parent().find("[name='beizhu']").val('');
//		$(this).parent().parent().parent().find("[name='jine']").val('').attr('readonly',false);
//		$('.check').removeClass("check2").addClass("check1");
//		$('.chazhc').css('display','none');
//		$('#checkYinpian').removeClass("check1").addClass("check2");
//		$('#checkHaocai').parent().parent('.modal-seh-leixing').css('display','none');
//	}
//	$(this).parent('ul').html('').css('display','none');
//	$("#shangpinjqcz").modal();
//	$('#shangpinmc').val(mingcchen);
//	$('#shengchancj').val('');
//	$('#gongyings').val('');
//	$('#checkHaocai').removeClass("check2").addClass("check1");
//	$('#checkBenzs').removeClass("check1").addClass("check2");
//	$('.modal-seh-laiyuan').css('display','none');
//	showJingq();
//});

function huoQuGuangBiao(yuanshu,msg){
	notifyWarning(msg);
	yuanshu.focus();
};
//点击保存时
vilidateform();
function vilidateform() {
   	  $('#formSave').on('valid.form', function(e){
			var flag = true;
			var flag2 =true;
			var guangBiao = true;
			var west =$(".western-medicine").css("display");
			var chinese =$(".chinese-medicine").css("display");
			//成药处方
			if(west=="block"){
	 			$('.western-medicine').each(function(){
	 				$(this).find("tbody tr").each(function(){
 	 	  				var yz1=$(this).find('.cgmdc-input1').val();
 	 	  				var yz2=$(this).find('.cgmdc-input2').val();
 	 	  				var yz3=$(this).find('.cgmdc-input3').val();
 	 	  				var yz4=$(this).find('.cgmdc-input4').val();
	 	 	  			var yz51=$(this).find('.cgmdc-input51').val();
 	 	  				var yz52=$(this).find('.cgmdc-input52').val();
 	 	  				var yz61=$(this).find('.cgmdc-input61').val();
 	 	  				var yz62=$(this).find('.cgmdc-input62').val();
	 	  				if(yz1!=""||yz3!=""||yz4!=""||yz51!=""||yz52!=""||yz61!=""||yz62!=""){
	 	  					if(yz1==""){
	 	  						$(this).find('.cgmdc-input1').addClass('n-invalid');
	 	  					if(guangBiao)
	 	  					huoQuGuangBiao($(this).find('.cgmdc-input1'),'请完成成药名称');
	 	  					guangBiao = false;
	 	  					}
	 	  					if(yz3==""){
	 	  					$(this).find('.cgmdc-input3').addClass('n-invalid');
	 	  				if(guangBiao)
	 	  				huoQuGuangBiao($(this).find('.cgmdc-input3'),'请完成成药用法');
	 	  				guangBiao = false;
	 	  					}
	 	  					if(yz4==""){
	 	  					$(this).find('.cgmdc-input4').addClass('n-invalid');
	 	  				if(guangBiao)
	 	  				huoQuGuangBiao($(this).find('.cgmdc-input4'),'请完成成药用药频率');
	 	  				guangBiao = false;
	 	  					}
	  					if(yz51==""){
		 	 	  			if(guangBiao){
		 	 	  				if($(this).find('.cgmdc-input52').val()=="适量"){	
		 	 	  				}else{
		 	 	  					$(this).find('.cgmdc-input51').addClass('n-invalid');
		 	 	  					huoQuGuangBiao($(this).find('.cgmdc-input51'),'请完成成药每次剂量数');
		 	 	  					guangBiao = false;
		 	 	  				}
		 	 	  			}
	  					}
	 	  				if(yz52==""){
	 	  					$(this).find('.cgmdc-input52').addClass('n-invalid');
	 	  				if(guangBiao)
	 	  				huoQuGuangBiao($(this).find('.cgmdc-input52'),'请完成成药每次剂量单位');
	 	  				guangBiao = false;
	 	  					}
	 	  					if(yz61==""){
	 	  					$(this).find('.cgmdc-input61').addClass('n-invalid');
	 	  				if(guangBiao)
	 	  				huoQuGuangBiao($(this).find('.cgmdc-input61'),'请完成成药开药数量');
	 	  				guangBiao = false;
	 	  					}
	 	  				if(yz62==""){
	 	  				$(this).find('.cgmdc-input62').addClass('n-invalid');
	 	 	  			if(guangBiao)
	 	 	  			huoQuGuangBiao($(this).find('.cgmdc-input62'),'请进入库存模块，维护药品');
	 	 	  			guangBiao = false;
	 	  					}
	 	  					
	 	  				}
	 	  				if(yz1==""||yz3==""||yz4==""||yz51==""||yz52==""||yz61==""||yz62==""){
	  	  	  			  	return false;
	  					}
	 				});
	 			});
			}
	 			//草药处方
				if(chinese=="block"){
	 			$('.chinese-medicine').each(function(){
	 				$(this).find("tbody tr").each(function(){
	 	  				var yz1=$(this).find('.cgmdc-input1').val();
	 	  				var yz2=$(this).find('.cgmdc-input2').val();
	 	  				var yz3=$(this).find('.cgmdc-input3').val();
	 	  				if(yz1!=""||yz2!=""){
	 	  					if(yz1==""){
	 	  						$(this).find('.cgmdc-input1').addClass('n-invalid');
 	 	  					if(guangBiao)
 	 	  					huoQuGuangBiao($(this).find('.cgmdc-input1'),'请完成饮片名称');
 	 	  						guangBiao = false;
	 	  					}
	 	  					if(yz2==""){
	 	  					$(this).find('.cgmdc-input2').addClass('n-invalid');
 	 	  				if(guangBiao)
 	 	  				huoQuGuangBiao($(this).find('.cgmdc-input2'),'请完成饮片数量');
 	 	  				guangBiao = false;
	 	  					}
	 	  					if(yz1==""||yz2==""){
	 	  	  	  			  return false;
	 	  					}
	 	  				}
	 					
	 				})
	 			});
				}
              //判断是否点击了删除按钮
		       if(!xuanzeypFlagbf){
				  xuanzeypFlag = true;
		       };
				//提交西药
				if(guangBiao&&west=="block"&&xuanzeypFlag){
					var chengyaoyp = tableDataToJson("chengyaoyp");
					var caoyaoyp = tableDataToJson("caoyaoyp");
					$('#chengyaoypId').attr('value',chengyaoyp);
					$('#caoyaoypId').attr('value',caoyaoyp);
					$('#btnSubmitc').attr('disabled',true);
					$.ajax({
			    		url:'./chufangmb/xinjiancfmb',
			    		 beforeSend: function () {
		 					$("#loading").css({"display":"block","z-index":"5"});
		 					 },
		 					 complete: function () {
		 						$("#loading").css({"display":"none","z-index":"5"});
		 					 },
			    		type:'POST',
			    		data:$('#formSave').serializeArray(),
			    		success:function(data) {
		 						if (data == MSG_CHONGFUBZ) {
		 							notifyWarning("该处方在诊所中已存在");
		 							$('#btnSubmitc').attr('disabled',false);
		 							return false;
		 						}
		 						var sjc=new Date().getTime();
								var msg='成药处方保存成功';
								A =0;
								msg=encodeURI(encodeURI(msg));
				    			$("#cedan").load(path+"/views/zhensuo/chufangmb.jsp?msg="+msg+"&sjc="+sjc);
				    			return false; 
			    		}
			    	});
					
				}
				//提交中药
				if(guangBiao&&chinese=="block"&&xuanzeypFlag){
					var chengyaoyp = tableDataToJson("chengyaoyp");
					var caoyaoyp = tableDataToJson("caoyaoyp");
					$('#chengyaoypId').attr('value',chengyaoyp);
					$('#caoyaoypId').attr('value',caoyaoyp);
					$('#btnSubmitc').attr('disabled',true);
					$.ajax({
			    		url:'./chufangmb/xinjiancfmb',
			    		type:'POST',
			    		 beforeSend: function () {
		 					$("#loading").css({"display":"block","z-index":"5"});
		 					 },
		 					 complete: function () {
		 						$("#loading").css({"display":"none","z-index":"5"});
		 					 },
			    		data:$('#formSave').serializeArray(),
			    		success:function(data) {
		 						if (data == MSG_CHONGFUBZ) {
		 							notifyWarning("该处方在诊所中已存在");
		 							$('#btnSubmitc').attr('disabled',false);
		 							return false;
		 						}
		 						var sjc=new Date().getTime();
								var msg='草药处方保存成功';
								A =0;
								msg=encodeURI(encodeURI(msg));
			    				$("#cedan").load(path+"/views/zhensuo/chufangmb.jsp?msg="+msg+"&sjc="+sjc);
			    				return false; 
			    		}
			    	});
				}
   	  });
}
var jixing = '';
//用法点击聚焦事件
$(document).on('focusin','[name="yongfa"]',function(){
	getYongfazd(this,jixing);
});
//药品点击第一行取消enter事件
$(document).on("focus",".yaopinmc",function(){
	enterToTab = false;
});
$(document).on("focusout",".yaopinmc",function(){
	if($(this).val()==''){
		xuanzeypFlag = true;
	}
});
//点击药品名称li
$(document).on("click",".yaopinmcul li.xuanzeli",function(){
	xuanzeypFlag = true;
	var id = $(this).attr('index');
	var iszs = $(this).attr('iszs');
	var yaopin = getYaopinById(id,iszs);
	fillchufangmb(id,iszs,yaopin,$(this));
});

//点击成药草药切换
$(document).on('click','.radio-label',function(){
	  $(this).addClass("on").siblings().removeClass("on");
	  if($("#west-label").hasClass("on")){//成药显示
		  	jixing = '';
	  		$(".g-m-chinese").css("display","none");
	  		$(".chinese-medicine .yongyypl").css("display","none");
	  		$(".chinese-medicine .yongfa").css("display","none");
	  		$(".g-m-west").css("display","block");
	  }else{//草药显示
		  	jixing = '饮片';
	  		$(".g-m-chinese").css("display","block");
	  		$(".chinese-medicine .yongyypl").css("display","inline-block");
	  		$(".chinese-medicine .yongfa").css("display","inline-block");
	  		$(".g-m-west").css("display","none");
	  }; 
});
//成药药品添加一行
$(document).off("focusout",'.western-medicine tbody tr .wm-medicine-name');
$(document).on('focusout','.western-medicine tbody tr .wm-medicine-name',function(){
	if(yanhouzhsj){
		var $parents = $(this).parent().parent().parent('tbody');
		var $parent = $parents.children("tr");
		var len=$parent.length;
	    var isLast = $parents.find(".wm-medicine-name").last().is($(this));
	    if(isLast&&$(this).val()!=""){
	    	$(this).parent().parent('tr').after(shengchengchengyyhMoney(len)); 
	    }
	    yanhouzhsj = false;
	}
});
//在草药表格后面添加一行
$(document).off("focusout",'.chinese-medicine tbody tr .wm-medicine-name');
$(document).on('focusout','.chinese-medicine tbody tr .wm-medicine-name',function(){
	if(yanhouzhsj){
		var $parents = $(this).parent().parent().parent('tbody');
		var $parent = $parents.children("tr");
		var len=$parent.length;
	    var isLast = $parents.find(".wm-medicine-name").last().is($(this));
	    if(isLast&&$(this).val()!=""){
	    	$(this).parent().parent('tr').after(shengchengcaoyyhMoney(len)); 
	    }
	    yanhouzhsj = false;
	}
	return false;
});
//移除草药行事件
$(document).on("click",".pointer3",function(){
        var $this=$(this);
        var $parent=$this.parent();
        var $tr=$parent.parent().parent();
        var chinese=$tr.parent().parent().parent();
        var length=chinese.find('tbody tr').length;
        var length=chinese.find("tbody tr").length;
        
        var $parents = $(this).parent().parent().parent('tbody');
        var wmName =$this.parents("tr").find(".wm-medicine-name");
        var isLast = $parents.find(".wm-medicine-name").last().is(wmName);
        
	if ((length<=1)||isLast) {
		$this.parent().parent().find("input:text").val("").removeClass("n-invalid");
		$this.parent().parent().find(".g-wmfinp-warning").css("display","none");
		$this.parent().parent().find(".g-wmfinp-danger").css("display","none");
	} else {
		$(this).popover('hide');
		$(this).parent().parent().remove();
        $parent.slideUp(300,function(){
            $tr.find(".zymb-number").each(function(i,e){
                $(e).text('饮片'+(i+1)+'：');
            });
            $tr.find(".wm-paixu").each(function(i,e){
                $(e).val(+(i+1));
            });
        });
        }
       xuanzeypFlagbf = false;
});
//移除成药行事件
$(document).on('click','.pointer2',function(){
	 var $this=$(this);
     var $parent=$this.parent();
     var $tr=$parent.parent().parent();
     var western=$tr.parent().parent().parent();
	var length=western.find('tbody tr').length;
	
	var $parents = $(this).parent().parent().parent('tbody');
    var wmName =$this.parents("tr").find(".wm-medicine-name");
    var isLast = $parents.find(".wm-medicine-name").last().is(wmName);
	if ((length<=1)||isLast) {
		$this.parent().parent().find("input:text").val("").removeClass("n-invalid");
		$this.parent().parent().find(".g-wmfinp-warning").css("display","none");
		$this.parent().parent().find(".g-wmfinp-danger").css("display","none");
	} else {
		$(this).popover('hide');
		$(this).parent().parent().remove();
		$parent.slideUp(300,function(){
            $tr.find(".wm-paixu").each(function(i,e){
                $(e).val(+(i+1));
            });
        });
	}
    xuanzeypFlagbf = false;

});

//点击用药频率li
$(document).on("click",".yongyyaoplul li",function(){
	var bText = $(this).attr('index');
	$(this).parent().parent().find('.yongyypl').val(bText).removeClass("n-invalid");;
	$(".f-input-li").css("display","none");
	$(this).parent().parent().parent().parent().find("input:visible:not('.wm-group')").each(function(){
		if($(this).val()==""){
			$(this).focus();
			return false;
		}
	})
}); 
//点击用法li
$(document).on("click",".yongfaul li",function(){
	var bText = $(this).text();
	$(this).parent().parent().find('.yongfa').val(bText).removeClass("n-invalid");;
	$(".f-input-li").css("display","none");
	$('#hz_serch').val("");
	$(this).parent().parent().parent().parent().find("input:visible:not('.wm-group')").each(function(){
		if($(this).val()==""){
			$(this).focus();
			return false;
		}
	});
});
$(document).on('input','.yaopinmc',function(){
	var parents = $(this).parents('.western-medicine');
	if($(parents).attr('class')!=undefined) {
		getYaopin(this,2, '1');
	}else{
		getYaopin(this,1, '1');
	}
});

//整体去掉input的autocomplete
$("input:text").attr("autocomplete","off");
//离开时给提示
$("#formSave").keyup(function(){
	A++;
});	
window.onbeforeunload = function(){
		 if(A>0){
			 return "编辑内容没有保存，是否离开？";
		 }
};
//取消时
$(".btn-xymb-cancel").click(function(){
	if(A>0){
		//判断是否离开
		if(confirm("编辑内容没有保存，是否离开？")){
			A = 0;
			$("#cedan").load(path+"chufangmb.jsp");
			return false; 
		}else{
			
		}
		
	}else{
		$("#cedan").load(path+"chufangmb.jsp");
		return false; 
	}
});
//回车转Tab
//检查控件是否可见
function checkobjvisual(e) {


    var objvis = false;
    if (e) {
        if (e.offsetHeight > 0) {
            objvis = true;
        }
        if (e.offsetTop > 0) {
            objvis = true;
        }
        
         if (e.readOnly == true) {
             objvis = false;  
       }  
      
    }
    return objvis;
}



//查找下一个控件
function focunext(next_id) {
    var code;
    if (!e) {
        var e = window.event;
    }
    if (e.keyCode) {
        code = e.keyCode;
    }
    else if (e.which) {
        code = e.which;
    }
    if (code == 13) {


        if (next_id)
        {document.getElementById(next_id).focus(); }
        else {
            var inputList = document.getElementsByTagName("input");
            // 循坏这个集合，包括了所有的input。
            var nextindex;
            nextindex = -1;
            for (i = 0; i < inputList.length; i++) {
                if (inputList[i] == document.activeElement) {
                    var acobj = document.activeElement;
                    nextindex = i + 1;
                    
                    while ((!checkobjvisual(inputList[nextindex])) && (nextindex <= inputList.length)) {
                        nextindex = nextindex + 1;
                    }
                    if (inputList[nextindex])  inputList[nextindex].focus();
                    break;
                }
            }
            
        }
    }
};
document.onkeydown = function(e) {
	    var code;
	    if (!e) {
	        var e = window.event;
	    }
	    if (e.keyCode) {
	        code = e.keyCode;
	    }
	    else if (e.which) {
	        code = e.which;
	    }
	    if (code == 8) {
	        if (document.activeElement.readOnly == true || document.activeElement.disabled == true)
	        { return false; }
	    }
	    if (code == 13) {
	        if (document.activeElement.type == "textarea") {
	            return;
	        }
	        if (document.activeElement.type != "submit" && document.activeElement.type != "button") {
	 
	             event.keyCode = 9;
	             if(!enterToTab){
			    		enterToTab = true;
			    }else{
			    	focunext();
			    }
	            return false;
	        }
	    }
	   
}
